package com.yuanxin.mpaas;


import static com.facebook.react.bridge.UiThreadUtil.runOnUiThread;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.alipay.mobile.h5container.api.H5BridgeContext;
import com.alipay.mobile.h5container.api.H5Page;
import com.alipay.mobile.h5container.service.H5Service;
import com.alipay.mobile.nebula.provider.H5ViewProvider;
import com.alipay.mobile.nebula.provider.MPH5OnKeyDownProvider;
import com.alipay.mobile.nebula.provider.TinyOptionMenuViewProvider;
import com.alipay.mobile.nebula.util.H5Utils;
import com.alipay.mobile.nebula.view.AbsTinyOptionMenuView;
import com.alipay.mobile.nebula.view.H5NavMenuView;
import com.alipay.mobile.nebula.view.H5PullHeaderView;
import com.alipay.mobile.nebula.view.H5TitleView;
import com.alipay.mobile.nebula.view.H5WebContentView;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableNativeMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.mpaas.framework.adapter.api.MPFramework;
import com.mpaas.mas.adapter.api.MPLogger;
import com.mpaas.nebula.adapter.api.MPNebula;
import com.mpaas.nebula.adapter.api.MPTinyHelper;
import com.mpaas.nebula.adapter.api.MpaasNebulaUpdateCallback;
import com.yuanxin.mpaas.view.H5TitleViewImpl;
import com.yuanxin.mpaas.view.TinyNavigationBar;
import com.yuanxin.mpaas.view.TinyOptionMenuView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;


public class RNMPaasModule extends ReactContextBaseJavaModule {
    public HashMap<String, H5BridgeContext> callbacks = new HashMap<>();
    private final ReactApplicationContext reactContext;
    public static boolean hideTitle;
    public TinyNavigationBar newH5TitleView;
    public static List<TinyNavigationBar> pageList = new ArrayList<>();
    private SharedPreferences sp;
    public RNMPaasModule(ReactApplicationContext reactContext) {
        super(reactContext);
        this.reactContext = reactContext;
        sp = reactContext.getSharedPreferences("mpaasFlag", 0);
    }

    @Override
    public String getName() {
        return "RNMpaas";
    }

    @ReactMethod
    public void LaunchMini(String appId, ReadableMap userInfo, boolean hideTitle, Callback callBack) {
        Log.i(getName(), "123321--启动小程序" + appId);
        this.hideTitle = hideTitle;
        HashMap<String, Object> map = userInfo.toHashMap();
        Bundle bundle = new Bundle();
        StringBuffer query = new StringBuffer();
        for (String key : map.keySet()) {
            if (key.equals("query")) {//放入query里面的参数
                HashMap<String, Object> mapValue = (HashMap<String, Object>) map.get(key);
                for (String key1 : mapValue.keySet()) {
                    query.append(key1 + "=" + Uri.encode(mapValue.get(key1).toString()) + "&");
                }
                bundle.putString(key, query.toString());
                Log.i(getName(), "123321--启动小程序 key=" + key);
                Log.i(getName(), "123321--启动小程序 key-value=" + query.toString());
            } else {
                bundle.putString(key, map.get(key).toString());
                Log.i(getName(), "123321--启动小程序 key=" + key);
                Log.i(getName(), "123321--启动小程序 key-value=" + map.get(key).toString());
            }
        }
        Log.i(getName(), "123321--启动小程序 pageString=" + bundle.toString());
        setCustomView(callBack);
        MPNebula.startApp(appId, bundle);


    }

    @ReactMethod
    public void ScanQRLaunchMini(String uri, ReadableMap userInfo, Callback callback) {
      Log.i(getName(),"123321--启动小程序");
        this.hideTitle = true;
        HashMap<String, Object> map = userInfo.toHashMap();
        Bundle param = new Bundle();
        StringBuffer query = new StringBuffer();
        for (String key : map.keySet()) {
            if (key.equals("query")) {//放入query里面的参数
                HashMap<String, Object> mapValue = (HashMap<String, Object>) map.get(key);
                for (String key1 : mapValue.keySet()) {
                    query.append(key1 + "=" + Uri.encode(mapValue.get(key1).toString()) + "&");
                }
                param.putString(key, query.toString());
                Log.i(getName(), "123321--启动小程序 key=" + key);
                Log.i(getName(), "123321--启动小程序 key-value=" + query.toString());
            }
        }
        Log.i(getName(), "123321--启动小程序 query.toString()=" + param.toString());
//        param.putString("query", query.toString()); //设置参数
        setCustomView(callback);
        MPTinyHelper.getInstance().launchIdeQRCode(Uri.parse(uri), param);
    }

    /**
     * RN 调用mpaas小程序给小程序发消息
     *
     * @param callbackId
     * @param readableMap
     */
    @ReactMethod
    public void callbackTiny(String callbackId, ReadableMap readableMap) {
//      Log.e("JSApiPlugin","callbackTiny");
        H5BridgeContext h5BridgeContext = callbacks.get(callbackId);
        if (h5BridgeContext != null) {
            ReadableNativeMap readableNativeMap = (ReadableNativeMap) readableMap;
            HashMap<String, Object> map = readableNativeMap.toHashMap();
            String jsonString = JSONObject.toJSONString(map);
//          Log.e("JSApiPlugin","callbackTiny callbackId="+jsonString);
            h5BridgeContext.sendBridgeResult(JSONObject.parseObject(jsonString));
            callbacks.remove(callbackId);
        }
    }

    /**
     * RN 调用mpaas小程序给小程序发渠道消息
     *
     * @param callbackId
     * @param readableMap
     */
    @ReactMethod
    public void callbackTinyChannel(String callbackId, ReadableMap readableMap) {
        H5BridgeContext h5BridgeContext = callbacks.get(callbackId);
        if (h5BridgeContext != null) {
            ReadableNativeMap readableNativeMap = (ReadableNativeMap) readableMap;
            HashMap<String, Object> map = readableNativeMap.toHashMap();
            H5Service h5Service = MPFramework.getExternalService(H5Service.class.getName());
            final H5Page h5Page = h5Service.getTopH5Page();
            if (null != h5Page) {
                JSONObject jo = new JSONObject(map);
                // native 向小程序发送事件的方法
                // 第一个是事件名称，第二个是参数，第三个默认传 null
                h5Page.getBridge().sendDataWarpToWeb(callbackId, jo, null);
            }
        }
    }

    /**
     * 用户报活埋点并注册id
     *
     * @param userID
     */
    @ReactMethod
    public void registerID(String userID) {
        Log.e("JSApiPlugin", "registerID=" + userID);
        MPLogger.setUserId(userID);//用户报活埋点
    }

    /**
     * 退出清空id
     */
    @ReactMethod
    public void loginOUt() {
        Log.e("JSApiPlugin", "loginOUt");
        MPLogger.setUserId(null);//用户报活埋点
    }

    @ReactMethod
    public void startWebView(String title, String url, String userAgent, ReadableMap info) {
        Log.e("JSApiPlugin", "startUrl");
//        MPNebula.startUrl("https://officewebapps.sinooceangroup.com/p/PowerPointFrame.aspx?PowerPointView=ReadingView&WOPISrc=https%3a%2f%2fworkflow.sinooceangroup.com%2fTHRWebApi%2fMaterialWopi%2fwopi%2ffiles%2fv3%2ffaae61de-e280-4134-898f-bda791b0be91&access_token=vmAt1l87Rao9sHAy7M9JaNP%2bO58NrI9BCwOza62YtZfzxchm0uUJrZxoLTfn0NH1VqBUSI0SSifvs%2bZWUr9uNP4fJeMJlmrDDnQ8AbPlU7vF2%2fU5lBDChGorsxRl8N1ZHcX5WO7yYh%2fo4%2b9c%2fSQHdfmYwP%2bDqYqzXk3YWFCYIOY5W1exqO1yDIex7PYvBqR1G0eRq1YIFSbKSNtRHTkD39LjVIVYjQpNIwddI8SY%2fqPvHaJ3yBdHGnCzVu1kz1B47R25Z3UhnULnm%2fUov1e%2f82m3JVOpv7RCerjGBRIEotg6xOppyV8MrRjILSu%2f8mvJTDzB18SySupPxE41MOErixsziDrkbRqSiUDpyzWucCCevYDoB7bXvAM7WG2gQ9DtFh1L%2f5uXuEfxKMgcSLCYtufJYb3%2fzphpAWm8zJaRuHbH0V75GuniNDiUYr4SaHUow7gVTV82WfNFymJxRRZqZ6R2aQ%2bS56YCaRp9SGzKHE0%3d");
        Intent intent = new Intent(getCurrentActivity(), WebViewActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("url", url);
        intent.putExtra("userAgent", userAgent);
        if (info.hasKey("waterStr")) {
            intent.putExtra("waterStr", info.getString("waterStr"));
        }
        getCurrentActivity().startActivity(intent);
    }

    public void startWebView(String title, String url, String userAgent, String waterStr) {
        Log.e("JSApiPlugin", "startUrl");
//        MPNebula.startUrl("https://officewebapps.sinooceangroup.com/p/PowerPointFrame.aspx?PowerPointView=ReadingView&WOPISrc=https%3a%2f%2fworkflow.sinooceangroup.com%2fTHRWebApi%2fMaterialWopi%2fwopi%2ffiles%2fv3%2ffaae61de-e280-4134-898f-bda791b0be91&access_token=vmAt1l87Rao9sHAy7M9JaNP%2bO58NrI9BCwOza62YtZfzxchm0uUJrZxoLTfn0NH1VqBUSI0SSifvs%2bZWUr9uNP4fJeMJlmrDDnQ8AbPlU7vF2%2fU5lBDChGorsxRl8N1ZHcX5WO7yYh%2fo4%2b9c%2fSQHdfmYwP%2bDqYqzXk3YWFCYIOY5W1exqO1yDIex7PYvBqR1G0eRq1YIFSbKSNtRHTkD39LjVIVYjQpNIwddI8SY%2fqPvHaJ3yBdHGnCzVu1kz1B47R25Z3UhnULnm%2fUov1e%2f82m3JVOpv7RCerjGBRIEotg6xOppyV8MrRjILSu%2f8mvJTDzB18SySupPxE41MOErixsziDrkbRqSiUDpyzWucCCevYDoB7bXvAM7WG2gQ9DtFh1L%2f5uXuEfxKMgcSLCYtufJYb3%2fzphpAWm8zJaRuHbH0V75GuniNDiUYr4SaHUow7gVTV82WfNFymJxRRZqZ6R2aQ%2bS56YCaRp9SGzKHE0%3d");
        Intent intent = new Intent(getCurrentActivity(), WebViewActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("url", url);
        intent.putExtra("userAgent", userAgent);
        intent.putExtra("waterStr", waterStr);
        getCurrentActivity().startActivity(intent);
    }

    public void backTinyApp() {
        if (newH5TitleView != null) {
            newH5TitleView.backTinyApp();
        }
    }

    /**
     * 更新所有小程序
     */
    @ReactMethod
    public void updateAllApp() {
        Log.e("JSApiPlugin", "updateAllApp");
        MPNebula.updateAllApp(new MpaasNebulaUpdateCallback() {//检查更新小程序版本。
            @Override
            public void onResult(final boolean success, final boolean isLimit) {
                super.onResult(success, isLimit);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (success) {
                            Toast.makeText(reactContext, "更新成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(reactContext, "更新失败", Toast.LENGTH_SHORT).show();

                        }
                    }
                });
            }
        });
    }

    public String saveCallback(H5BridgeContext context, JSONObject jsonObject) {
        String callbackId = jsonObject.getString("callbackid");
        if (callbackId == null) {
            callbackId = UUID.randomUUID().toString();
        }
        callbacks.put(callbackId, context);
        return callbackId;
    }

    /**
     * 给RN发消息
     *
     * @param context
     * @param jsonObject
     */
    public void sendMessageToRN(String callbackId, H5BridgeContext context, JSONObject jsonObject) {
//       Log.e("JSApiPlugin","mpaas sendMessageToRN"+jsonObject.toString());
        WritableMap params = Arguments.createMap();
        params.putMap("data", JsonConvert.jsonToReact(jsonObject));
        params.putString("callbackid", "" + callbackId);
//       Log.e("JSApiPlugin","mpaas sendMessageToRN tinyToRn");
        this.reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit("tinyToRn", params);
    }

    /**
     * 给RN发渠道消息
     *
     * @param context
     * @param jsonObject
     */
    public void sendChannelMessageToRN(String callbackId, H5BridgeContext context, JSONObject jsonObject) {
//       Log.e("JSApiPlugin","mpaas sendChannelMessageToRN"+jsonObject.toString());
        WritableMap params = Arguments.createMap();
        String channelId = callbackId;
        if (channelId != null) {
            params.putMap("data", JsonConvert.jsonToReact(jsonObject));
            params.putString("channelId", "" + channelId);
            this.reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                    .emit("tinyToRnChannel", params);
        }
//       Log.e("JSApiPlugin","mpaas sendChannelMessageToRN tinyToRn");
    }

    private void setCustomView(final Callback callBack) {
        pageList.clear();
        MPNebula.setCustomViewProvider(new H5ViewProvider() {
            @Override
            public H5TitleView createTitleView(Context context) {
                // 返回自定义 title
//                newH5TitleView = new H5TitleViewImpl(context,callBack);
                newH5TitleView=new TinyNavigationBar(context,callBack);
                pageList.add(newH5TitleView);
                newH5TitleView.getContentView().setVisibility(hideTitle?View.GONE:View.VISIBLE);
                Log.e("JSApiPlugin", "createTitleView pageList.size()==" + pageList.size());
               return newH5TitleView;
            }

            @Override
            public H5NavMenuView createNavMenu() {
                return null;
            }

            @Override
            public H5PullHeaderView createPullHeaderView(Context context, ViewGroup viewGroup) {
                return null;
            }

            @Override
            public H5WebContentView createWebContentView(Context context) {
                return null;
            }
        });
        // 自定义小程序右上角配置栏
        H5Utils.setProvider(TinyOptionMenuViewProvider.class.getName(), new TinyOptionMenuViewProvider() {
            @Override
            public AbsTinyOptionMenuView createView(Context context) {
                TinyOptionMenuView tinyOptionMenuView = new TinyOptionMenuView(context);
                tinyOptionMenuView.hideOptionMenu();
//                tinyOptionMenuView.setTitleGone(View.GONE);
                return tinyOptionMenuView;
            }
        });
        H5Utils.setProvider(MPH5OnKeyDownProvider.class.getName(), new MPH5OnKeyDownProvider() {
            @Override
            public boolean needIntercept(H5Page page, int keyCode, KeyEvent intent) {
                Log.e("JSApiPlugin", "needIntercept pageList.size()==" + pageList.size());
                if (pageList.size() > 2) {//判断是否为首页，小程序有个默认启动页，然后是首页，所以大于2
                    pageList.remove(pageList.size() - 1);
                    return false;
                } else {
                    return true;
                }
            }

            @Override
            public boolean onKeyDown(H5Page page, int keyCode, KeyEvent intent) {
                if (pageList.size() > 0) {
                    newH5TitleView.backTinyApp();
                }
                return false;
            }
        });
    }
}
